{% extends "base.html" %}
{% block title %}
    {{ image.title }}
{% endblock %}
{% block content %}
    <h1>{{ image.title }}</h1>
    {% load thumbnail %}
    {% thumbnail image.image "300" as im %}
        <a href="{{ image.image.url }}">
            <img src="{{ im.url }}" class="image-detail">
        </a>
    {% endthumbnail %}
    {% with total_likes=image.user_like.count user_like=image.user_like.all %}
        <div class="image-info">
            <div>
            <span class="count">
                <span class="total">{{ total_likes }}</span> 人喜欢
            </span>
            <span class="count">
                <span class="total">{{ total_views }}</span> 次查看
            </span>
                <a href="#" data-id="{{ image.id }}"
                   data-action="{% if request.user in user_like %}un{% endif %}like"
                   class="like button">
                    {% if request.user in user_like %}
                        取消喜欢
                    {% else %}
                        喜欢
                    {% endif %}
                </a>
            </div>
            {{ image.description|linebreaks }}
            <div class="image-likes">
                {% for user in image.user_like.all %}
                    <div>
                        <img src="{{ user.profile.photo.url }}">
                        <p>{{ user.first_name }}</p>
                    </div>
                {% empty %}
                    没有人喜欢这张图片。
                {% endfor %}
            </div>
        </div>
    {% endwith %}
{% endblock %}
{% block domready %}
        $('a.like').click(function (e) {
            e.preventDefault();
            $.post('{% url "images:like" %}',
                {
                    id: $(this).data('id'),
                    action: $(this).data('action'),
                },
                function (data) {
                    if (data['status'] == 'ok') {
                        var previous_action = $('a.like').data('action');
                        // 切换 data-action
                        $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like');
                        // 切换 link text
                        $('a.like').text(previous_action == 'like' ? '取消喜欢' : '喜欢');
                        // 更新 total likes
                        var previous_likes = parseInt($('span.count .total').text());
                        $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1);
                    }

                });
        });
{% endblock %}

